package com.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Writer;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.utils.DBUtil;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=request.getSession(true);
		request.setCharacterEncoding("UTF-8");
//		Writer out = response.getWriter();
		
		try {
			Connection conn=DBUtil.getConn();
			Statement stm=conn.createStatement();
			ResultSet rs= stm.executeQuery("select file from content where fatieid=3");
			rs.next();
			//将输出编码转换成网络传输编码ISO8859-1,以防止文件名称乱码
			String path=new String(rs.getString("file").getBytes("utf-8"),"ISO8859-1").replace('/', '\\');
			//得到文件名
			String fileName=path.substring(path.lastIndexOf(File.separator)+1);
			//告诉浏览器输出内容为流 。注意：在设置Content-Disposition头字段之前，一定要设置Content-Type头字段。 
			response.setContentType("application/octet-stream");
			//Content-Disposition中指定的类型是文件的扩展名，并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的，点保存后，文件以filename的值命名，保存类型以Content中设置的为准。 
			response.setHeader("content-disposition", "attachment;filename="+fileName);
			FileInputStream fis=new FileInputStream(path);
			int len=0;
			byte[] buf=new byte[1024];
			while((len=fis.read(buf))!=-1){
				response.getOutputStream().write(buf);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
